import list from './list';
import Cookie from 'js-cookie';
import { Suspense, useState } from 'react';
import Npro from '../components/nprogress';
import { RouteType } from '../interface/route';
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';

export default function index() {
    const [whiteList, setList] = useState(['/login', '/submit'])
    
    // 路由渲染之前
    function before(v: RouteType) {
        if (v.path === '/login') {
            if (Cookie.get('token')) {
                return <Navigate to='/'></Navigate>
            }
        }
        if (whiteList.find(item => item === v.path) && !Cookie.get('token')) {
            return <Navigate to='/login'></Navigate>
        }
        return v.element
    }
    // 递归渲染
    function render(list: RouteType[]) {
        return list.map((v, i) => {
            return <Route key={i} path={v.path} element={before(v)}>
                {
                    v.children && render(v.children)
                }
            </Route>
        })
    }

    return (
        <Suspense fallback={<Npro></Npro>}>
            <BrowserRouter>
                <Routes>
                    {
                        render(list)
                    }
                </Routes>
            </BrowserRouter>
        </Suspense>
    )
}
